from utils import *
from const import api_key, api_secret

INTERVAL = '30m'  # 周期
SYMBOL = 'ETHBTC'
LIMIT = 500  # 所取最近数据量，必须大于长线周期
TIMEOUT = 3  # 取数据网络等待时间
AMT = 20     # 满仓数量

def main_func():
    撤单U本位(api_key, api_secret, SYMBOL, 'buy_order')
    撤单U本位(api_key, api_secret, SYMBOL, 'sell_order')
    df = get_kline_U(SYMBOL, INTERVAL, LIMIT, TIMEOUT)
    df['m10'] = df['close'].rolling(10).mean()
    df['m30'] = df['close'].rolling(30).mean()
    df['s30'] = df['close'].rolling(30).std()
    df['m60'] = df['close'].rolling(60).mean()
    df['m360'] = df['close'].rolling(360).mean()
    df['sig1'] = (df['m30'] > df['m360']).apply(lambda x:1 if x else -1)
    df['sig2'] = (df['m10'] > df['m60'] + df['s30'])*1 + (df['m10'] < df['m60'] - df['s30'])*-1
    df['sig'] = (df['sig1'] + df['sig2'])/2

    m30 = df.loc[df.index[-2],'m30']
    m360 = df.loc[df.index[-2], 'm360']
    m10 = df.loc[df.index[-2], 'm10']
    m60 = df.loc[df.index[-2], 'm60']
    s30 = df.loc[df.index[-2], 's30']
    sig1 = df.loc[df.index[-2],'sig1']
    sig2 = df.loc[df.index[-2], 'sig2']
    sig = df.loc[df.index[-2], 'sig']

    m30,m360,m10,m60,s30 = [round(x,5) for x in [m30,m360,m10,m60,s30]]

    sig_pos = sig*AMT
    sig_pos = round(sig_pos,2)

    df_pos = 获取U本位持仓(api_key, api_secret)
    current_pos = df_pos.loc[SYMBOL,'positionAmt']
    dif_pos = sig_pos - current_pos
    dif_pos = round(dif_pos,2)

    df_bid,df_ask = 获取深度U本位(api_key, api_secret, SYMBOL, 5)
    bid1 = df_bid.loc[0,'price']
    ask1 = df_ask.loc[0,'price']

    logger.info(f'm30:{m30},m360:{m360}')
    logger.info(f'sig1:{sig1},m10:{m10},m60+s30:{round(m60+s30,5)}')
    logger.info(f'sig2:{sig2},m10:{m10},m60-s30:{round(m60-s30,5)}')
    logger.info(f'信号:{sig}')
    logger.info(f'信号持仓:{sig_pos}')
    logger.info(f'当前持仓:{current_pos}')

    if abs(dif_pos) >= 0.02:
        logger.info(f'当前持仓需要调整，{dif_pos}')
        if dif_pos > 0:
            PARAMS = 准备挂单参数U本位(api_key, api_secret, SYMBOL, 'BUY', bid1,abs(dif_pos), 'buy_order')
            res = private_restapi_binance(**PARAMS)
            res_info = json.loads(res.text.encode())
        else:
            PARAMS = 准备挂单参数U本位(api_key, api_secret, SYMBOL, 'SELL', ask1,abs(dif_pos), 'sell_order')
            res = private_restapi_binance(**PARAMS)
            res_info = json.loads(res.text.encode())
    else:
        logger.info('当前持仓无需调整')


while True:
    main_func()
    time.sleep(300)